package com.zcy;

import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.runtime.client.EPEventService;
import com.zcy.event.MyEvent;
import com.zcy.util.EsperBuilder;
import com.zcy.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

/**
 * 14.3.12. Expiry Expression Window (expr or win:expr)
 * 最灵活的窗口，可以动态调整
 */
@Slf4j
public class ExprWindow extends TimeUtils {

    private static final String _Expire01 = "@name('first_length') select sum(num) from MyEvent#expr(newest_timestamp - oldest_timestamp < 2000)";

    /**
     * 保留事件的最后2秒
     * sum is : 10
     * sum is : 30
     * sum is : 30
     * sum is : 40
     */
    @Test
    public void firstLengthTest() {
        EsperBuilder esperBuilder = new EsperBuilder(_Expire01, new Class[]{MyEvent.class});

        esperBuilder.startCompile();

        EPEventService epEventService = esperBuilder.startDeploy((eventBeans, eventBeans1, epStatement, epRuntime) -> {
            for (int i = 0; i < eventBeans.length; i++) {
                EventBean eventBean = eventBeans[i];
                log.info("sum is : {}", eventBean.get("sum(num)"));
            }
        });

        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(10).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 1L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(20).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 2L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(30).build(), MyEvent.class.getSimpleName());
        sleep(TimeUnit.SECONDS, 2L);
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(40).build(), MyEvent.class.getSimpleName());

        sleep(TimeUnit.SECONDS, 40L);
    }

}
